import {
  View,
  Button,
  Image,
  Text,
  ScrollView,
  CommonEvent,
  Picker,
  Textarea,
  Input,
} from "@tarojs/components";
import React, { Component, ReactNode } from "react";
import i1 from "./images/i1.png";
import i2 from "./images/i2.png";
import i3 from "./images/i3.png";
import i4 from "./images/i4.png";
import i5 from "./images/i5.png";
import i6 from "./images/i6.png";
import i7 from "./images/i7.png";
import i8 from "./images/i8.png";

import Taro from "@tarojs/taro";
import Req, { BASE_URL } from "../../utils/request";

import {
  AtSearchBar,
  AtList,
  AtListItem,
  AtTabs,
  AtTabsPane,
  AtButton,
  AtIcon,
} from "taro-ui";
import "./index.scss";
import { delay, isEmpty } from "../../utils/kit";

export default class ExpenseManagement extends Component {
  state = {
    value: "",
    loading: true,
    hasMore: true,
    currentPage: 1,
    total: 0,
    list: [],
    info: {},
    futuresProjectId: null, //全局ID

    current: 0, //默认选中计划
    progressCurrent: 0, //计划-实际

    year: "", //所属年份
    memo: "", //完成目标
    planDate: "", //提交日期

    logs: [], //计划明细
    planId: "", //计划表Id

    finishTag: 0, //

    isDisabled: false, //是否禁用
  };

  onChange = (val: string) => {
    this.setState({
      value: val,
    });
  };
  onActionClick = () => {
    console.log("开始搜索");
  };
  _onBackRefresh = (v) => {
    if (v.force) {
      this.initData(v.futuresProjectId);
    }
  };
  _onBackRefreshLog = (v) => {
    if (v.force) {
      this.initLog();
    }
  };
  componentDidMount(): void {
    // this.loadData();
    this.initData();
    Taro.eventCenter.on("refreshData", this._onBackRefresh);
    Taro.eventCenter.on("refreshLog", this._onBackRefreshLog);
  }
  handleAdd = () => {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      Taro.navigateTo({
        url: `/pages/expense-form/index?id=${router.params.id}`,
      });
    }
  };
  onScrollDetchEnd = () => {
    if (this.state.hasMore) {
      delay(300).then(() => {
        this.loadData();
      });
    } else {
      this.setState({
        loading: false,
      });
    }
  };
  componentWillUnmount(): void {
    Taro.eventCenter.off("refreshData", this._onBackRefresh);
    Taro.eventCenter.off("refreshLog", this._onBackRefreshLog);
  }
  loadData = () => {
    const { currentPage, list, futuresProjectId, current } = this.state;
    this.setState({
      loading: true,
    });
    let _url = "/project/expenses/list";
    if (current === 0) {
      _url = "/project/fulfil/list";
    }
    Req.get(_url, {
      futuresProjectId,
      pageNum: currentPage,
      pageSize: 10,
    })
      .then((r) => {
        if (r.rows.length < 10) {
          this.setState({
            hasMore: false,
          });
        }
        this.setState({
          total: r.total,
          list: list.concat([...r.rows] as any),
          currentPage: currentPage + 1,
          loading: false,
        });
      })
      .catch((e) => {
        this.setState({
          loading: false,
        });
      });
  };
  onRefresh = () => {
    console.log("刷新");
  };
  initData = async (futuresProjectId = null) => {
    const { router } = Taro.getCurrentInstance();
    let _futuresProjectId = router?.params.id;
    if (futuresProjectId) {
      _futuresProjectId = futuresProjectId;
    }

    if (_futuresProjectId) {
      this.setState(
        {
          currentPage: 1,
          hasMore: true,
          list: [],
          futuresProjectId: _futuresProjectId,
        },
        () => {
          this.loadData();
        }
      );

      try {
        const r1 = await Req.get(
          "/project/expenses/census",
          {
            futuresProjectId: _futuresProjectId,
          },
          {
            loading: false,
          }
        );
        if (r1.code === 200 && r1.rows.length) {
          this.setState({
            info: r1.rows[0],
          });
        }
        const _type = {
          0: "1", // 进度计划
          1: "2", //支出计划
        };
        const r2 = await Req.get(
          "/project/plan/info",
          {
            futuresProjectId: _futuresProjectId,
            type: _type[this.state.current],
          },
          {
            loading: false,
          }
        );

        this.setState({
          finishTag: r2.data?.finishTag,
          planId: r2.data?.id ?? "",
          year: (r2.data?.year ?? new Date().getFullYear()) + "",
          memo: r2.data?.memo ?? "",
          planDate: r2.data.planDate,
          logs: r2.data?.log ?? [],

          isDisabled: !isEmpty(r2.data?.id),
        });
      } catch (e) {}
    }
  };
  componentDidShow() {
    const { router } = Taro.getCurrentInstance();
    this.setState({
      futuresProjectId: router?.params.id,
    });
  }

  initLog = async () => {
    const { futuresProjectId } = this.state;
    if (futuresProjectId) {
      try {
        const _type = {
          0: "1", // 进度计划
          1: "2", //支出计划
        };
        const r2 = await Req.get(
          "/project/plan/info",
          {
            futuresProjectId: futuresProjectId,
            type: _type[this.state.current],
          },
          {
            loading: false,
          }
        );
        this.setState({
          logs: r2.data.log,
        });
      } catch (e) {}
    }
  };
  goToDetail = (row) => {
    Taro.navigateTo({
      url: `/pages/expense-detail/index?id=${row.id}`,
    });
  };
  render(): ReactNode {
    const {
      info,
      current,
      progressCurrent,
      year,
      memo,
      planDate,
      futuresProjectId,
      logs,
      planId,
      finishTag,
      isDisabled,
    }: any = this.state;

    const _tabs = [
      {
        title: "进度",
        type: "1",
      },
      {
        title: "支出",
        type: "2",
      },
    ];

    const _firstImg = (img: string): string => {
      if (img) {
        return BASE_URL + img.split(",")[0];
      }
      return i8;
    };

    return (
      <View className="em-container">
        <View className="top-header p15">
          <AtSearchBar
            className="em-search-bar"
            value={this.state.value}
            onChange={this.onChange}
            onActionClick={this.onActionClick}
          />
        </View>
        <ScrollView
          enhanced
          showScrollbar={false}
          className="em-c-wrapper"
          refresherEnabled
          scrollY
          onScrollToLower={this.onScrollDetchEnd}
          onRefresherRefresh={this.onRefresh}
        >
          <View>
            <View className="em-c-top">
              <Text className="e-c-t1">{info.projectTitle}</Text>
              <View className="e-c-v1">
                <View className="e-c-v2">
                  <Text className="e-c-t2">{info.bondsTitle}</Text>
                </View>
                <View className="e-c-v3">
                  <Text className="e-c-t3">{info.inAmout}</Text>
                  <Text className="e-c-t4">万元</Text>
                </View>
                <View className="e-c-v3">
                  <Text className="e-c-t3 e-c-t5">{info.outAmount}</Text>
                  <Text className="e-c-t4">万元</Text>
                </View>
              </View>
            </View>
            {/* 进度-支出 */}
            <AtTabs
              current={current}
              tabList={_tabs}
              className="tabs-bg"
              onClick={(v) => {
                this.setState(
                  {
                    current: v,
                  },
                  () => {
                    this.initData();
                  }
                );
              }}
            >
              {_tabs.map((tab, index) => (
                <AtTabsPane key={index} current={current} index={index}>
                  <View className="tabs-zhichu">
                    <View
                      onClick={() => {
                        this.setState({
                          progressCurrent: 0,
                        });
                      }}
                      className={`zhichu-tab-item ${
                        progressCurrent === 0 ? "zhichu-tab-item_active" : ""
                      }`}
                    >
                      <View className="zhichu-tab-item_inner">计划</View>
                    </View>
                    <View
                      onClick={() => {
                        this.setState({
                          progressCurrent: 1,
                        });
                      }}
                      className={`zhichu-tab-item ${
                        progressCurrent === 1 ? "zhichu-tab-item_active" : ""
                      }`}
                    >
                      <View className="zhichu-tab-item_inner">实际</View>
                    </View>
                  </View>
                  <View className="outer-container">
                    {progressCurrent === 0 && (
                      <View>
                        <AtList className="no-border-top">
                          <Picker
                            disabled={isDisabled}
                            value={year}
                            onChange={(e) => {
                              this.setState({
                                year: e.detail.value,
                              });
                            }}
                            mode="date"
                            fields="year"
                          >
                            <AtListItem
                              className="form-list-item form-label-required"
                              title={"所属年份"}
                              arrow="down"
                              note={
                                <View>
                                  <Text>
                                    {isEmpty(year) ? "请选择年份" : year + "年"}
                                  </Text>
                                </View>
                              }
                            />
                          </Picker>

                          {tab.type === "1" && (
                            <AtListItem
                              title={"完成目标"}
                              className="form-label-required form-list-item no-active-effect-item remark-form-item no-arrow-space"
                              note={
                                <View>
                                  <Textarea
                                    disabled={isDisabled}
                                    value={memo}
                                    onInput={(e) => {
                                      this.setState({
                                        memo: e.detail.value,
                                      });
                                    }}
                                    className="remark-textarea"
                                    placeholder="请输入完成目标"
                                  />
                                </View>
                              }
                            />
                          )}

                          <Picker
                            value={planDate}
                            disabled={isDisabled}
                            onChange={(e) => {
                              this.setState({
                                planDate: e.detail.value,
                              });
                            }}
                            mode="date"
                            fields="day"
                          >
                            <AtListItem
                              className="form-list-item no-arrow-space form-label-required"
                              title={"提交日期"}
                              note={
                                <View className="if-date-content">
                                  <Text>
                                    {isEmpty(planDate)
                                      ? "请选择日期"
                                      : planDate}
                                  </Text>
                                  <Image className="date-icon" src={i5} />
                                </View>
                              }
                            />
                          </Picker>
                        </AtList>

                        <AtButton
                          className="primary-btn-color m-20"
                          circle
                          type="primary"
                          onClick={() => {
                            if (isDisabled) {
                              Taro.showModal({
                                title: "提示",
                                content: "是否确认修改？",
                                success: (res) => {
                                  if (res.confirm) {
                                    this.setState({
                                      isDisabled: false,
                                    });
                                  }
                                },
                              });
                            } else {
                              const _type = {
                                0: "1", // 进度计划
                                1: "2", //支出计划
                              };

                              if (isEmpty(year)) {
                                Taro.showToast({
                                  title: "所属年份不能为空！",
                                  icon: "none",
                                  duration: 2000,
                                });
                                return false;
                              }
                              if (isEmpty(planDate)) {
                                Taro.showToast({
                                  title: "提交日期不能为空！",
                                  icon: "none",
                                  duration: 2000,
                                });
                                return false;
                              }
                              if (current === 0 && isEmpty(memo)) {
                                Taro.showToast({
                                  title: "完成目标不能为空！",
                                  icon: "none",
                                  duration: 2000,
                                });
                                return false;
                              }

                              let _url = "/project/plan/add";
                              let paramObj = {
                                futuresProjectId,
                                type: _type[current],
                                year,
                                memo,
                                planDate,
                              };
                              if (planId) {
                                _url = "/project/plan/edit";
                                paramObj["id"] = planId;
                              }

                              Req.post(_url, { ...paramObj })
                                .then((r) => {
                                  this.initData();
                                })
                                .catch((e) => {});
                            }

                            // if (isEmpty(planId)) {
                            //   const _type = {
                            //     0: "1", // 进度计划
                            //     1: "2", //支出计划
                            //   };
                            //   let _url = "/project/plan/add";
                            //   let paramObj = {
                            //     futuresProjectId,
                            //     type: _type[current],
                            //     year,
                            //     memo,
                            //     planDate,
                            //   };
                            //   if (planId) {
                            //     _url = "/project/plan/edit";
                            //     paramObj["id"] = planId;
                            //   }
                            //   Req.post(_url, { ...paramObj })
                            //     .then((r) => {
                            //       this.initData();
                            //     })
                            //     .catch((e) => {});
                            // } else {
                            //   Taro.showModal({
                            //     title: "提示",
                            //     content: "是否确认修改？",
                            //     success: (res) => {
                            //       if (res.confirm) {

                            //       }
                            //     },
                            //   });
                            // }
                          }}
                        >
                          {!isDisabled ? "提交" : "编辑"}
                        </AtButton>
                        <View className="plan-title-box">
                          <Text className="plan-title">计划详情</Text>
                          {!isEmpty(planId) && finishTag === 0 && (
                            <View
                              onClick={() => {
                                // Taro.navigateTo({
                                //   url: `/pages/plan-form/index?planId=${planId}&current=${current}`,
                                // });
                                logs.push({
                                  ifModify: true,
                                  planId,
                                  month: "",
                                  ratio: "",
                                });
                                this.setState({
                                  logs,
                                });
                              }}
                              className="plan-add"
                            >
                              <Image mode="widthFix" src={i1} />
                              <Text>新增</Text>
                            </View>
                          )}
                        </View>
                        <View className="plan-table">
                          <View className="plan-tr">
                            <View className="plan-th">月份</View>
                            <View className="plan-th">
                              {current === 0 ? "进度(%)" : "支出(%)"}
                            </View>
                            {current === 0 ? (
                              <View className="plan-th">备注</View>
                            ) : (
                              <View className="plan-th">金额（万元）</View>
                            )}
                            <View className="plan-th"></View>
                          </View>
                          {logs.map((item, index) => (
                            <View key={index} className="plan-tr">
                              <View className="plan-td">
                                {item.ifModify ? (
                                  <Picker
                                    value={(function () {
                                      if (typeof item.month === "number") {
                                        return item.month - 1;
                                      } else {
                                        return null;
                                      }
                                    })()}
                                    mode="selector"
                                    onChange={(e) => {
                                      item.month =
                                        (e.detail.value as number) + 1;
                                      logs[index] = item;
                                      this.setState({
                                        logs,
                                      });
                                    }}
                                    range={[
                                      "1月",
                                      "2月",
                                      "3月",
                                      "4月",
                                      "5月",
                                      "6月",
                                      "7月",
                                      "8月",
                                      "9月",
                                      "10月",
                                      "11月",
                                      "12月",
                                    ]}
                                  >
                                    <View>
                                      {isEmpty(item.month)
                                        ? "请选择"
                                        : item.month + "月"}
                                    </View>
                                  </Picker>
                                ) : (
                                  <View>{item.month}月</View>
                                )}
                              </View>
                              <View className="plan-td">
                                {item.ifModify ? (
                                  <View>
                                    <Input
                                      placeholder="请输入"
                                      value={item.ratio}
                                      onInput={(e) => {
                                        item.ratio = e.detail.value;
                                        logs[index] = item;
                                        this.setState({
                                          logs,
                                        });
                                      }}
                                    />
                                  </View>
                                ) : (
                                  <View>{item.ratio}</View>
                                )}
                              </View>
                              <View className="plan-td">
                                {item.ifModify ? (
                                  current === 0 ? (
                                    <View>
                                      <Input
                                        placeholder="请输入"
                                        value={item.memo}
                                        onInput={(e) => {
                                          item.memo = e.detail.value;
                                          logs[index] = item;
                                          this.setState({
                                            logs,
                                          });
                                        }}
                                      />
                                    </View>
                                  ) : (
                                    <View>
                                      <Input
                                        placeholder="请输入"
                                        value={item.amount}
                                        onInput={(e) => {
                                          item.amount = e.detail.value;
                                          logs[index] = item;
                                          this.setState({
                                            logs,
                                          });
                                        }}
                                      />
                                    </View>
                                  )
                                ) : current === 0 ? (
                                  <View>{item.memo}</View>
                                ) : (
                                  <View>{item.amount}</View>
                                )}
                              </View>
                              <View className="plan-td">
                                {finishTag === 0 && (
                                  <>
                                    <Image
                                      onClick={() => {
                                        if (!item.id) {
                                          logs.splice(index, 1);
                                          this.setState({
                                            logs,
                                          });
                                          return false;
                                        }
                                        Taro.showModal({
                                          title: "提示",
                                          content: "确认删除？",
                                          success: (res) => {
                                            if (res.confirm) {
                                              Req.post(
                                                "/project/plan/details/" +
                                                  item.id
                                              ).then((r) => {
                                                if (r.code === 200) {
                                                  this.initLog();
                                                }
                                              });
                                            }
                                          },
                                        });
                                      }}
                                      className="plan-btn"
                                      src={i6}
                                    />
                                    {!item.ifModify && (
                                      <Image
                                        onClick={() => {
                                          item.ifModify = true;
                                          logs[index] = item;
                                          this.setState({
                                            logs,
                                          });
                                          // Taro.navigateTo({
                                          //   url: `/pages/plan-form/index?current=${current}&planId=${planId}&lid=${item.id}&month=${item.month}&ratio=${item.ratio}`,
                                          // });
                                        }}
                                        className="plan-btn"
                                        src={i7}
                                      />
                                    )}

                                    {item.ifModify && (
                                      <AtIcon
                                        onClick={() => {
                                          let _url =
                                            "/project/plan/details/add";
                                          if (item?.id) {
                                            _url = "/project/plan/details/edit";
                                          }

                                          if (isEmpty(item.month)) {
                                            Taro.showToast({
                                              title: "月份不能为空！",
                                              icon: "none",
                                              duration: 2000,
                                            });
                                            return false
                                          }
                                          if(current === 0){
                                            if(isEmpty(item.ratio)){
                                              Taro.showToast({
                                                title: "进度不能为空！",
                                                icon: "none",
                                                duration: 2000,
                                              });
                                              return false;
                                            }
                                          }
                                          if (current === 1) {
                                            if (
                                              isEmpty(item.ratio) &&
                                              isEmpty(item.amount)
                                            ) {
                                              Taro.showToast({
                                                title:
                                                  "支出值和金额至少填一个！",
                                                icon: "none",
                                                duration: 2000,
                                              });
                                              return false;
                                            }
                                          }

                                          Req.post(_url, {
                                            ...item,
                                          })
                                            .then((r) => {
                                              Taro.showToast({
                                                title: "操作成功！",
                                                icon: "none",
                                                duration: 2000,
                                              });
                                              this.initData();
                                            })
                                            .catch((e) => {});
                                        }}
                                        value="check"
                                        size={"20"}
                                        color="#2A71ED"
                                      />
                                    )}
                                  </>
                                )}
                              </View>
                            </View>
                          ))}
                        </View>
                      </View>
                    )}

                    {progressCurrent === 1 && (
                      <View>
                        <View className="mingxi-v1">
                          <Text className="mx-t1">明细</Text>
                          <Image mode="widthFix" src={i4} />
                          <Button
                            onClick={() => {
                              if (current === 1) {
                                this.handleAdd();
                              } else if (current === 0) {
                                Taro.navigateTo({
                                  url: `/pages/fulfill-form/index?futuresProjectId=${futuresProjectId}`,
                                });
                              }
                            }}
                            className="text-button"
                          >
                            <Image className="icon-1" src={i1} />
                            新增
                          </Button>
                        </View>
                        <AtList>
                          {current === 1 &&
                            this.state.list.map((item2: any, index2) => (
                              <AtListItem
                                onClick={() => {
                                  Taro.navigateTo({
                                    url: `/pages/expense-detail/index?id=${item2.id}`,
                                  });
                                }}
                                className="no-arrow-space"
                                key={index2}
                                title={
                                  <View className="em-item-title">
                                    <View className="em-i-text">
                                      <Image className="em-i-t1" src={i3} />
                                      <Text className="em-i-t2">
                                        {item2.amount}
                                      </Text>
                                      <Text className="em-i-t3">万元</Text>
                                    </View>
                                    <Text className="em-i-t4">
                                      {item2.payDate}
                                    </Text>
                                  </View>
                                }
                                note={
                                  <View className="em-item-content">
                                    <View className="em-i-c-v1">
                                      <Image
                                        className="em-i-c-v1-img"
                                        src={i2}
                                      />
                                      <Text className="em-i-c-v1-t1">
                                        {item2.payee?.name}
                                      </Text>
                                    </View>
                                    <Text className="em-i-c-v1-t2">
                                      {item2.memo}
                                    </Text>
                                  </View>
                                }
                              />
                            ))}

                          {current === 0 &&
                            this.state.list.map((item2: any, index2) => (
                              <AtListItem
                                onClick={() => {
                                  Taro.navigateTo({
                                    url: `/pages/fulfill-form/index?futuresProjectId=${futuresProjectId}&fid=${item2.id}`,
                                  });
                                }}
                                className="no-arrow-space"
                                key={index2}
                                note={
                                  <View
                                    style={{
                                      display: "flex",
                                    }}
                                  >
                                    <Image
                                      mode="aspectFill"
                                      className="om-list-note-i1"
                                      src={_firstImg(item2.img)}
                                    />
                                    <View className="om-content">
                                      <View className="two-line-max-text">
                                        {item2.memo}
                                      </View>
                                      <View className="om-c-bottom">
                                        <View>
                                          <Text className="oln-label">
                                            进度(%)
                                          </Text>
                                          {item2.ratio}
                                        </View>
                                        <View>
                                          <Text className="oln-label">
                                            截止日期
                                          </Text>
                                          {item2.deadline}
                                        </View>
                                      </View>
                                    </View>
                                  </View>
                                }
                              />
                            ))}
                        </AtList>
                        <View className="em-center-text">
                          <Text>
                            {this.state.hasMore ? "加载中..." : "没有更多了"}
                          </Text>
                        </View>
                      </View>
                    )}
                  </View>
                </AtTabsPane>
              ))}
            </AtTabs>
          </View>
        </ScrollView>
      </View>
    );
  }
}
